import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:local_coffee/components/c_appbar/custom_appbar.dart';
import 'package:local_coffee/components/c_button/index.dart';
import 'package:local_coffee/components/hex.dart';
import 'package:local_coffee/components/rgba.dart';
import 'package:local_coffee/routes/index.dart';
import 'package:local_coffee/utils/global.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginMail extends StatefulWidget {
  
  LoginMail({
    Key key
  }) : super(key: key);

  _LoginMailState createState() => _LoginMailState();
}

class _LoginMailState extends State<LoginMail> {
  
  static Map email = {
    'value': null,
    'verify': true
  };

  static Map code = {
    'value': null,
    'verify': true
  };

  SharedPreferences preferences;

  // 开始倒计时 时间
  int startTime;

  // 当前倒计时 时间
  int countDownTime = 0;

  // 总倒计时 时长
  final int speed = 60;

  Timer _timer;

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () async {
      preferences = await SharedPreferences.getInstance();

      startTime = preferences.getInt('startTime');

      int nowTime = G.getTime();

      if (startTime != null && startTime > 0) {
        if (nowTime - startTime > 60) {
          preferences.remove('startTime');
        } else {
          countDown();
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  /// 获取验证码
  getEmailCode() async {
    try {
      var res = await G.req.verificationCode.getMailCode(mail: email['value']);

      if (res.data = null) {
        return;
      }

      G.toast('获取验证码成功');
      startTime = G.getTime();
      countDown();
    } catch (e) {
      G.toast('获取验证码失败');
    }
  }

  countDown() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      int nowTime = G.getTime();
      int result = speed - (nowTime - startTime);
      if (result < 0) {
        preferences.remove('startTime');
        _timer?.cancel();
      }

      setState(() {
        countDownTime = result;
      });
    });
  }

  /// 登录
  login() async {
    if (!email['verify'] || email['value'] == null) {
      return G.toast('邮箱不正确');
    }
    if (!code['verify'] || code['value'] == null) {
      return G.toast('验证码不正确');
    }

    // 登录前移除 `user`, 否则登录会提示 token 错误
    preferences.remove('local_user');

    try {
      var res = await G.req.user.register(
        code: code['value'], 
        email: email['value'], 
        pwd: '123456',
        autoLogin: true
      );
      
      var data = res.data;

      if (data == null) {
        return null;
      }

      await getUserDetail(data['data']['token']);

      await G.toast('登录成功');

      G.pushNamed(N.mine);
    } catch (e) {
      G.toast('登录失败');
    }
  }

  /// 获取用户详情
  getUserDetail(String token) async {
    var res = await G.req.user.detail();

    var data = res.data;

    Map json = data['data']['base'];
    json['token'] = token;

    G.user.init(json);
  }

  /// 获取验证码
  Container buildGetEmailCode() {
    return Container(
      child: CButton.normal(
        child: Text(
          countDownTime <= 0 ? '获取验证码' 
            : countDownTime < 10 ? '0 $countDownTime' : '$countDownTime'
        ),
        color: email['verify'] && email['value'] != null
          ? RGBA.rgba557a9d
          : RGBA.rgbaa6a6a6,
        onPressed: () {
          if (countDownTime > 0) {
            return;
          }
          getEmailCode();
        }
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: customAppBar(
        context: context,
        borderBottom: false
      ),
      body: Container(
        color: HEX.hexfff,
        padding: EdgeInsets.only(left: 35, right: 35, top: 87),
        child: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(bottom: 20),
              width: 80,
              height: 94,
              child: Image.asset(
                P.login1,
                fit: BoxFit.cover,
              ),
            ),
            // 邮箱
            Container(
              height: 55,
              decoration: BoxDecoration(
                border: G.borderBottom()
              ),
              child: TextField(
                keyboardType: TextInputType.emailAddress,
                decoration: InputDecoration(
                  counterText: '',
                  border: InputBorder.none,
                  hintText: 'enter mail',
                  hintStyle: TextStyle(
                    fontSize: 14
                  )
                ),
                onChanged: (e) {
                  RegExp regExp = RegExp("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+");
                  setState(() {
                    email['value'] = e;
                    email['verify'] = regExp.hasMatch(e);
                  });
                },
              ),
            ),
            Container(
              height: 55,
              decoration: BoxDecoration(
                border: G.borderBottom()
              ),
              child: Row(
                children: <Widget>[
                  Flexible(
                    child: TextField(
                      maxLength: 4,
                      keyboardType: TextInputType.number,  
                      decoration: InputDecoration(
                        counterText: '',
                        border: InputBorder.none,
                        hintText: '验证码',
                        hintStyle: TextStyle(
                          fontSize: 14
                        )
                      ),
                      onChanged: (e) {
                        setState(() {
                          code['value'] = e;
                          code['verify'] = e.length == 4 ? true : false;
                        });
                      },
                    ),
                  ),
                  Container(
                    height: 25,
                    decoration: BoxDecoration(
                      border: Border(
                        left: BorderSide(
                          color: RGBA.rgbaf2f2f2
                        )
                      )
                    ),
                  ),
                  buildGetEmailCode()
                ],
              ),
            ),
            // 登录
            Container(
              margin: EdgeInsets.only(top: 20),
              child: CButton.normal(
                width: 300,
                child: Text('确定'),
                bgColor: RGBA.rgba88afd5,
                color: HEX.hexfff,
                onPressed: () => login()
              ),
            ),
            // 协议
            Container(
              margin: EdgeInsets.only(top: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '点了确定，即表示已阅读并同意',
                    style: TextStyle(
                      fontSize: 12,
                      color: RGBA.rgba999999
                    ),
                  ),
                  InkWell(
                    child: Text(
                      '《注册会员服务条款》',
                      style: TextStyle(
                        color: RGBA.rgba557a9d,
                        fontSize: 12
                      ),
                    ),
                    onTap: () => Navigator.pushNamed(context, N.userAgreement),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}